<template>
    <div class="Login">
        <div class="w1440">
            <div class="text">当好党和政府职能部门的助手<br>当好社会力量参与国善公益的桥梁纽带</div>
            <div class="LoginBox slideTxt">
                <div class="hd">
                    <ul>
                        <li :class="{ on: activeIndex === 0 }" @click="setActive(0)"><a>密码登录</a></li>
                        <li :class="{ on: activeIndex === 1 }" @click="setActive(1)"><a>验证码登录</a></li>
                    </ul>
                </div>
                <div class="bd">
                    <div class="Form">
                        <el-form class="form" :model="formData" ref="formRef" :rules="rules">
                            <div v-if="activeIndex === 0" class="password-box">
                                <el-form-item prop="mobile">
                                    <el-input v-model="formData.mobile" size="large" placeholder="请输入手机号"
                                        :prefix-icon="Iphone" />
                                </el-form-item>
                                <el-form-item prop="pwd">
                                    <el-input type="password" size="large" v-model="formData.pwd" placeholder="请输入密码"
                                        :prefix-icon="Lock" />
                                </el-form-item>
                            </div>
                            <!-- <ul v-if="activeIndex === 0">
                                <li>
                                    <div class="icon"><img src="../assets/images/user.png" alt=""></div>
                                    <input type="text" id="mobile" v-model="formData.mobile"
                                        :class="{ 'is-invalid': errors.mobile }" placeholder="请输入手机号" class="inputbox"
                                        autocomplete="mobile" />
                                    <div v-if="errors.mobile" class="error-message">{{ errors.mobile }}</div>
                                </li>
                                <li>
                                    <div class="icon"><img src="../assets/images/password.png" alt=""></div>
                                    <input type="password" id="password" v-model="formData.pwd"
                                        :class="{ 'is-invalid': errors.pwd }" placeholder="请输入登录密码" class="inputbox"
                                        autocomplete="pwd" />
                                    <div v-if="errors.pwd" class="error-message">{{ errors.pwd }}</div>
                                </li>
                            </ul> -->
                            <div v-if="activeIndex === 1" class="code-box">
                                <el-form-item prop="mobile">
                                    <el-input v-model="formData.mobile" size="large" placeholder="请输入手机号"
                                        :prefix-icon="Iphone" />
                                </el-form-item>
                                <el-form-item :prop="activeIndex == 1 ? 'code' : ''">
                                    <el-input v-model="formData.code" size="large" placeholder="请输入验证码"
                                        :prefix-icon="Lock" >
                                    <template #append>
                                        <span class="pointer" @click="getCode">{{codeStatus ? codeNumber+'s' : '获取验证码'}}</span>
                                    </template>
                                    </el-input>
                                    {{testCode}}
                                </el-form-item>
                            </div>
                            <div v-if="false" class="fogretbox">
                                <div class="check choose-box fl">
                                    <div class="checkbox">
                                        <input type="checkbox" id="remember" v-model="formData.remember" />
                                        <label for="remember" class="checkbox-label">记住账号</label>
                                    </div>
                                </div>
                                <!-- <a href="" class="fr">忘记密码？</a> -->
                                <div class="clear"></div>
                            </div>
                            <div class="formbtn">
                                <div class="pointer button" @click="submitForm">登录</div>
                            </div>
                        </el-form>
                    </div>


                </div>
                <div class="other">
                    还没有账号，<router-link to="/register">立即注册</router-link>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup name="Login">
import { userApi } from '@/api';
import { computed, ref, reactive, onBeforeMount } from 'vue';
import { useCommonStore } from '@/store/Common';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Iphone, Lock } from '@element-plus/icons-vue';

// 路由
const router = useRouter();

// 生命周期
onBeforeMount(() => {
    // 读取 sessionStorage 中的 token
    const storedToken = sessionStorage.getItem('token');
    if (storedToken) {
        router.push('/');
    }
})

// 页面数据
const activeIndex = ref(0);
// 表单数据
const formData = reactive({
    mobile: '18000000001',
    pwd: '123456',
    code: ''
})
// 表单验证错误信息
const rules = {
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6, max: 6, message: '验证码长度为 6 个字符', trigger: 'blur' }
    ]
}

// 公共store
const commonStore = useCommonStore();
// 读取 store 中的内容
const { token } = storeToRefs(commonStore);


// 方法
function setActive(index) {
    activeIndex.value = index;
    formRef.value.clearValidate();
}

/**
 * @name 提交表单
 */
const formRef = ref(null);
const codeStatus = ref(false);
const codeNumber = ref(60);
const testCode = ref('');
const getCode = () => {
    if(!formData.mobile) return ElMessage.error('请输入手机号');
    if(!/^1[3-9]\d{9}$/.test(formData.mobile)) return ElMessage.error('请输入正确的手机号');
    userApi.sendSmsCode({mobile: formData.mobile}).then((res) => {
        if(!codeStatus.value) {
            codeStatus.value = true;
            let timer = setInterval(() => {
                codeNumber.value--;
                if(codeNumber.value <= 0) {
                    clearInterval(timer);
                    codeStatus.value = false;
                    codeNumber.value = 60;
                }
            },1000)
        }
        testCode.value = res.msg;
    }).catch(err => { 
        codeStatus.value = false;
        codeNumber.value = 60;
     });
    
}
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            // 表单提交成功
            userApi.passwordAndCodeLogin({data: formData, path: activeIndex.value == 0 ? 'pwdLogin' : 'smsLogin'}).then((res) => {
                token.value = res.token;
                sessionStorage.setItem('token', res.token);
                router.push('/userInfo');
                ElMessage.success('登录成功');
            }).catch(err => { });
        }
    })
}

</script>
<style scoped>
.bd ul[v-if="activeIndex === 0"],
.bd ul[v-if="activeIndex === 1"] {
    display: block;
}

.error-message {
    font-size: 12px;
    position: absolute;
    color: red;
}
</style>